<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2023/12/8
 * Time: 17:49
 */

namespace app\ws\command;


use think\console\Command;
use think\console\Input;
use think\console\Output;
use Swoole\WebSocket\Server;

class Track extends Command
{
    /**
     * 配置指令
     * @return void
     */
    protected function configure(): void
    {
        $this->setName('websocket:track')
             ->setDescription('启动WebSocket服务器');
    }

    /**
     * 执行
     * @param Input  $input
     * @param Output $output
     * @return void
     */
        protected function execute(Input $input, Output $output): void
        {
            $config = config('swoole.websocket');
            // 创建日志文件
            $path = root_path() . 'runtime/ws/track.log';
            createLog($path);
            if ($config['enable']) {
                // 根据配置启动WebSocket服务器
                // 这里需要根据具体框架和WebSocket服务器组件来实现启动逻辑
                $handlerClass = new \app\ws\controller\WhTrack();//不适用静态调用,所以没有用配置中的类句柄
                //客户端与服务器握手成功后，会触发onOpen事件
                $server = new Server($config['host'], $config['port']);
                $server->on('open', [$handlerClass,"onOpen"]);
                $server->on('message', [$handlerClass, 'onMessage']);
                $server->on('close', [$handlerClass, 'onClose']);
                $server->set([
                    'heartbeat_check_interval' => $config['ping_interval'],
                    'heartbeat_idle_time'      => $config['ping_timeout'],
                    'log_file'                 => $path,
                    'log_level'                => 2,
                    'daemonize'                => false,//开启守护模式
                ]);
                $server->start();
            } else {
                $output->info('WebSocket未开启');
            }
        }
}